package com.runa.protocol.analysis;

import com.runa.protocol.enums.ModbusFunctionCode;
import com.runa.protocol.util.DigitalUtil;

/**
 * @author zhuj
 */
public class ModbusBufferRTUAnalysis extends MetaBufferAnalysis<byte[]> {

    @Override
    public int fill(byte[] data, int size,String netEquNo) {
        if (size < 3) {
            return -1;
        }
        ModbusFunctionCode funCode = ModbusFunctionCode.getByCode(data[1] & 0xff);
        int len;
        if (funCode.isReadOrWrite()) {
            len = (data[2] & 0xff) + 5;
        } else {
            len = 8;
        }
        if (size < len) {
            return -1;
        }
        int crc16 = DigitalUtil.calcCrc16(data, len-2);
        int rev16 = ((0xFF&data[len-1])<<8)+(0xFF & data[len-2]);
        if (crc16 == rev16) {
            int slave = data[0] & 0xff;
            int cap;
            if (funCode.isReadOrWrite()){
                cap = len - 5;
                System.arraycopy(data, 3, data, 0, cap);
            } else {
                cap = 4;
                System.arraycopy(data, 2, data, 0, cap);
            }
            buffer = data;
            createModbusResponse(slave, funCode, cap);
        } else {
            responseData = null;
            return 0;
        }
        return size - len;
    }

}
